package com.caocaog.market.finance.timetask;


import com.caocaog.market.finance.entity.FinanceLine;
import com.caocaog.market.finance.service.FinanceLineService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.IPUtils;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时结算任务
 */
@Slf4j
@Component
@EnableScheduling
@RequiredArgsConstructor
public class ScheduledSettlementTask {

    /**
     * 指定此端口号的服务才会执行定时任务
     */
    public static final Integer SCHEDULED_PORT = 9093;
    /**
     * 结算天数（从订单支付的时间往后递进3天就是结算时间）
     */
    public static final Integer SETTLEMENT_DAY = 3;

    private final FinanceLineService financeLineService;


    @Scheduled(cron = "0 0/1 * * * ?")
    public void execute() throws JobExecutionException {
        if (IPUtils.getTomcatPort() != SCHEDULED_PORT) return;

        // 获取所有需要结算的订单
        List<FinanceLine> needSettlements = financeLineService.findNeedSettlement(SETTLEMENT_DAY);
        // 没有需要结算的订单
        if (needSettlements.isEmpty()) return;
        // 执行结算
        Integer settledCount = financeLineService.updateFinanceLineSettled(needSettlements.stream().map(FinanceLine::getId).collect(Collectors.toList()));
        if (settledCount > 0) {
            log.info("定时结算任务执行成功，结算订单数：{}", settledCount);
        } else {
            log.error("定时结算任务执行失败，结算订单数：{}", settledCount);
        }

    }
}
